﻿using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using System;
using System.Linq;
using System.Windows.Forms;
using MapFormsApp.Services;
using MapFormsApp.Models;
using MapFormsApp.Helpers;

namespace MapFormsApp
{
    public partial class MainForm : Form
    {
        #region 控件与组件声明
        private AxToolbarControl _axToolbarControl;
        private AxTOCControl _axTOCControl;
        private TextBox _txtSearch;
        private Button _btnRoute;
        private ComboBox _cmbTravelMode;
        private MapManager _mapManager;
        private RoutingService _routingService;
        private QueryService _queryService;
        private DataManager _dataManager;
        #endregion

        #region 构造函数与初始化
        public MainForm()
        {
            InitializeComponent();
            InitializeGISComponents();
            BindEvents();
        }

        /// <summary>
        /// 初始化GIS组件（地图控件、服务类）
        /// </summary>
        private void InitializeGISComponents()
        {
            // 初始化数据访问层
            //_dataManager = new DataManager("D:\\Project\\MapFormsApp\\MapFormsApp\\MapFormsApp\\Data\\demo.gdb");

            // 初始化地图管理器
            IMapControl3 mapControl = axMapControl1.Object as IMapControl3;
            _mapManager = new MapManager(mapControl);
            _mapManager.LoadMapDocument("D:\\Project\\MapFormsApp\\MapFormsApp\\MapFormsApp\\Data\\demo.mxd");
            axMapControl1.Update();
            //// 初始化路径服务
            //INetworkDataset networkDataset = _dataManager.GetNetworkDataset("Pedestrian_ND");
            //_routingService = new RoutingService(networkDataset);

            // 初始化查询服务
            //_queryService = new QueryService(_mapManager.Map, _dataManager);

            // 初始化工具栏和TOC控件
            InitializeToolbar();
        }

        /// <summary>
        /// 初始化工具栏和TOC控件
        /// </summary>
        private void InitializeToolbar()
        {
            // 搜索框与按钮
            Panel controlPanel = new Panel { Dock = DockStyle.Top, Height = 40 };
            _txtSearch = new TextBox { Width = 200, Location = new System.Drawing.Point(10, 10) };
            _btnRoute = new Button { Text = "路径规划", Location = new System.Drawing.Point(220, 10) };
            _cmbTravelMode = new ComboBox { Items = { "步行", "骑行" }, SelectedIndex = 0, Location = new System.Drawing.Point(300, 10) };
            controlPanel.Controls.AddRange(new Control[] { _txtSearch, _btnRoute, _cmbTravelMode });
            Controls.Add(controlPanel);
        }
        #endregion

        #region 事件绑定
        private void BindEvents()
        {
            axMapControl1.OnMouseDown += AxMapControl_OnMouseDown;
            _btnRoute.Click += BtnRoute_Click;
            _txtSearch.KeyUp += TxtSearch_KeyUp;
        }
        #endregion

        #region 核心事件处理
        /// <summary>
        /// 地图点击事件（选择起点/终点）
        /// </summary>
        private void AxMapControl_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            try
            {
                IPoint clickPoint = _mapManager.ScreenToMap(e.x, e.y);

                // 查询点击位置的建筑
                Building building = _queryService.QueryByPoint(clickPoint).FirstOrDefault();
                if (building != null)
                {
                    ShowBuildingInfo(building);
                    IFeatureLayer buildingLayer = _mapManager.FindLayerByName("Buildings") as IFeatureLayer;

                    //创建高亮颜色（示例：红色）
                    IColor highlightColor = new RgbColorClass
                    {
                        Red = 255,
                        Green = 0,
                        Blue = 0
                    };

                    _mapManager.HighlightSelection(buildingLayer, highlightColor); // 添加第二个参数
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 路径规划按钮点击事件
        /// </summary>
        private void BtnRoute_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取起止点（示例：从界面输入或地图选择）
                IPoint start = GetSelectedPoint("起点");
                IPoint end = GetSelectedPoint("终点");

                // 计算路径
                using (RouteResult result = _routingService.CalculateRoute(start, end))
                {
                    if (result.IsSuccess)
                    {
                        // 显示路径
                        _mapManager.AddRouteLayer(result.PathGeometry);
                        ShowRouteDetails(result);
                    }
                    else
                    {
                        MessageBox.Show("未找到可行路径");
                    }
                }
            }
            catch (RoutingException ex)
            {
                MessageBox.Show($"路径计算错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 搜索框输入处理（模糊查询建筑）
        /// </summary>
        private void TxtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            var buildings = _queryService.QueryByName(_txtSearch.Text.Trim());
            if (buildings.Count > 0)
            {
                _mapManager.ZoomToGeometry(buildings[0].Geometry);
            }
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 显示建筑信息弹窗
        /// </summary>
        private void ShowBuildingInfo(Building building)
        {
            InfoWindow infoWindow = new InfoWindow(building);
            infoWindow.ShowDialog();
        }

        /// <summary>
        /// 显示路径详细信息
        /// </summary>
        private void ShowRouteDetails(RouteResult result)
        {
            RouteDetailsPanel panel = new RouteDetailsPanel(result);
            panel.Dock = DockStyle.Right;
            Controls.Add(panel);
        }

        /// <summary>
        /// 获取用户选择的点（示例：从地图标记获取）
        /// </summary>
        private IPoint GetSelectedPoint(string pointName)
        {
            // 实际项目中应从地图标记或界面输入获取坐标
            return GeometryHelper.CreatePoint(116.3974, 39.9093); // 示例坐标
        }
        #endregion

    }
}